package com.iyoudoock.citymine.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.widget.ImageView;

import com.iyoudoock.citymine.R;
import com.squareup.picasso.Picasso;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by Kvin on 2017/6/2.
 */
public class ImageUtils {

    public static final String BASE64_PREFIX = "data:image/png;base64,";

    /**
     * return default image
     */
    public static void display(Context context, String imageUri, ImageView iv) {
        Picasso.with(context)
                .load(imageUri)
                .placeholder(R.mipmap.ic_launcher)
                .error(R.mipmap.ic_launcher)
                .centerCrop()
                .resize(100, 100)
                .into(iv);
    }

    /**
     * convert bitmap to string
     */
    public static String convertBitmapToString(String path) {
        String out = "";
        try {
            Bitmap bitmap = compressInScale(path,400,400);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            out = BASE64_PREFIX + Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
            baos.close();
            bitmap.recycle();//recycle memory
        } catch (Exception e) {
            e.printStackTrace();
            return out;
        }
        return out;
    }

    /**
     * compress in scale
     */
    public static Bitmap compressInScale(String path, int w, int h) {
        int scale = 1;
        BitmapFactory.Options option = new BitmapFactory.Options();
        option.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, option);
        while (option.outWidth / scale > w || option.outHeight / scale > h) {
            scale += 1;
        }
        option.inSampleSize = scale;

        option.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, option);
    }
}
